package org.wu.spring.db.integration.compare.infrastructure.persistence.cassandra;

import com.datastax.oss.driver.api.core.CqlSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.wu.framework.core.utils.LazyListUtils;
import org.wu.framework.lazy.orm.core.config.enums.LazyDataSourceType;
import org.wu.framework.lazy.orm.core.factory.LazyTableUpsertConverterFactory;
import org.wu.framework.lazy.orm.core.persistence.conf.LazyColumn;
import org.wu.framework.lazy.orm.core.persistence.conf.LazyTableEndpoint;
import org.wu.framework.lazy.orm.core.source.adapter.SourceFactory;
import org.wu.framework.lazy.orm.database.lambda.domain.LazyPage;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import org.wu.spring.db.integration.compare.config.DbConfig;
import org.wu.spring.db.integration.compare.domain.model.sys.user.DbComparisonRepository;
import org.wu.spring.db.integration.compare.domain.model.sys.user.SysUser;
import org.wu.spring.db.integration.compare.enums.DatabaseType;
import org.wu.spring.db.integration.compare.enums.ExecuteType;
import org.wu.spring.db.integration.compare.infrastructure.persistence.DbComparisonRepositoryAbstract;

import java.net.InetSocketAddress;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
//@Component
public class LazyCassandraComparisonRepository extends DbComparisonRepositoryAbstract implements DbComparisonRepository {


    private final DbConfig dbConfig;
    private final CqlSession session;

    public LazyCassandraComparisonRepository(DbConfig dbConfig) {
        this.dbConfig = dbConfig;
        DbConfig.CassandraConfig cassandraConfig = dbConfig.getCassandraConfig();
        String host = cassandraConfig.getHost();
        int port = cassandraConfig.getPort();
        String localDatacenter = cassandraConfig.getLocalDatacenter();
        String username = cassandraConfig.getUsername();
        String password = cassandraConfig.getPassword();
        this.session = CqlSession.builder()
                .addContactPoint(new InetSocketAddress(host, port))
                .withLocalDatacenter(localDatacenter)
                .build();

    }

    /**
     * describe 批量新增
     *
     * @param rowSize    @return {@link Result <  List  < SysUser >>} 新增后领域对象集合
     * @param columnSize
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/
    @Override
    protected Result<List<SysUser>> doBatchStory(int rowSize, int columnSize) throws Exception {
        String schemaName = dbConfig.getSchemaName();
        String tableName = dbConfig.getTableName();

        // 创建数据库
        session.execute("create database if not exists {0};", Boolean.class, schemaName);
        // 删除表
        session.execute("drop table if exists {0}.{1}", Integer.class, schemaName, tableName);

        // 创建表
        Map<String, Object> rowData = getRowData(columnSize);

        LazyTableEndpoint<?> lazyTableEndpoint = SourceFactory
                .analyzeLazyTableFromMap(LazyDataSourceType.MySQL, schemaName, tableName, rowData);
        String creatTableSQL = lazyTableEndpoint.creatTableSQL();
        session.execute(creatTableSQL);

        boolean success = true;
        LocalDateTime startTime = LocalDateTime.now();
        try {

            List<Map<String, Object>> list=new ArrayList<>();

            for (int i = 0; i < rowSize; i++) {
                Map<String, Object>   rowDataItem = getRowData(columnSize);
                list.add(rowDataItem);
            }
            for (List<Map<String, Object>> maps : LazyListUtils.splitList(list, 1000)) {
                String sql = LazyTableUpsertConverterFactory.insertWeak(schemaName, tableName, maps);
                session.execute(sql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(DatabaseType.Cassandra, ExecuteType.batchStory, startTime, endTime, rowSize, columnSize, success);

        return ResultFactory.successOf();
    }

    /**
     * describe 分页查询多个
     *
     * @param rowSize    当前页数
     * @param columnSize
     * @return {@link Result<   LazyPage   <SysUser>>} 分页领域对象
     * @author Jia wei Wu
     * @date 2024/02/28 11:27 上午
     **/
    @Override
    protected Result<LazyPage<SysUser>> doFindPage(int rowSize, int columnSize) throws Exception {
        String schemaName = dbConfig.getSchemaName();
        String tableName = dbConfig.getTableName();
        // 查询表字段
//        String tableColumnListSql = SourceFactory.findTableColumnListSql(LazyDataSourceType.MySQL, schemaName, tableName);
//        Class<? extends LazyColumn> columnInfoClass = SourceFactory.findColumnInfoClass(LazyDataSourceType.MySQL);
//        List<? extends LazyColumn> lazyColumns = session.execute(tableColumnListSql, columnInfoClass);
//        String queryColumn = lazyColumns.subList(0, (Math.min(columnSize, lazyColumns.size()))).stream().map(LazyColumn::getColumnName).collect(Collectors.joining(","));


        boolean success = true;
        LocalDateTime startTime = LocalDateTime.now();
        try {
            // 过滤指定条数
            session.execute("select * from {0}.{1} limit {2}", Object.class,
                    schemaName,
                    tableName,
                    rowSize
            );
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        LocalDateTime endTime = LocalDateTime.now();
        storyRecord(DatabaseType.Cassandra, ExecuteType.findPage, startTime, endTime, rowSize, columnSize, success);


        return ResultFactory.successOf();
    }
}
